package light.head.controller.mobile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.AuditStatusDAO;
import light.head.dao.oa.ReimburseDAO;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageTemplateDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.RoleDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.AuditStatus;
import light.head.model.Reimburse;
import light.head.model.ReimburseItem;
import light.head.model.UserInfo;

/**
 * 报销申请审核
 * @author yy @date 2015-6-17
 *
 */
@Controller
@RequestMapping(Url.MOBILE_REIMBURSE)
public class MobileReimburseManagerController extends SupporterController{
	private ReimburseDAO reDAO;
	private OrganDAO organDAO;
	private AuditStatusDAO asDAO;
	private UserInfoDAO userDAO;
	private MessageTemplateDAO mtDAO;
	private MessageDAO msgDAO;
	private RoleDAO roleDAO;

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.MOBILE_REIMBURSE_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED, Parm.TIME1, Parm.TITLE, Parm.TIME2, Parm.PROJECT,Parm.ON,Parm.CN,Parm.PASS);
		
			// 获取根机构配置的物品申请流程节点
			if (reDAO.findByMap_1(organDAO.getSonCodeList(cu_organCode(request)), cu_roleCode(request), map, pb) == RESULT.SUCCESS) {
				// 讲对应的审核状态放到对应的
				Reimburse re = null;
				Double total = (double) 0;
				String a =map.get(Parm.PROJECT);
				for (Object o : pb.getResultList()) {
					re = (Reimburse) o;
					List<ReimburseItem> itemList = reDAO.findApplyItem(re.getCode());
					for (ReimburseItem item : itemList) {
						if (map.get(Parm.PROJECT) != null && map.get(Parm.PROJECT) != ""){
							if(item.getProject().equals(map.get(Parm.PROJECT))){
								total = total + item.getAmount();
							}
						} else {
							total = total + item.getAmount();
						}
					}
					re.setItemList(itemList);
					re.setAuditStatusList(asDAO.findByBusinessMc(Sys.B_FOUR, re.getCode()));
				}
				Integer rc = roleDAO.findName("出纳", organDAO.getRoot(cu_organCode(request)).getCode());
				if(rc != null && cu_roleCode(request) == rc){
					request.setAttribute(Parm.ROLE, rc);
				}
				request.setAttribute(Parm.PROJECT, a);
				request.setAttribute(Parm.TOTAL, total);
			}
		request.setAttribute(Parm.RP, cu_roleCode(request));
		request.setAttribute(Parm.CU, cu_code(request));
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.MOBILE_REIMBURSE_LIST);
	}

	// 单个申请单详情
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Reimburse a = reDAO.get(code);
			if (null != a) {
				a.setAuditStatusList(asDAO.findByBusinessMcRc(Sys.B_FOUR, a.getCode(), cu_roleCode(request)));
				List<ReimburseItem> list = reDAO.findApplyItem(code);
				a.setItemList(list);
				request.setAttribute(Parm.REIMBURSE, a);
				Integer rc = roleDAO.findName("出纳", organDAO.getRoot(cu_organCode(request)).getCode());
				if(rc != null && cu_roleCode(request) == rc){
					request.setAttribute(Parm.ROLE, rc);
				}
			}
		}
		return new ModelAndView(Url.REIMBURSE_MANAGER_DETAIL);
	}

	
	@RequestMapping(Url.UPDATEDESIGNATE_1)
	public void updateDesignate1(String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		// 查询当前申请信息是否已被当前用户审核
		List<AuditStatus> asList = asDAO.findByRcMcAuBusiness(cu_roleCode(request), Integer.parseInt(code), cu_code(request), Sys.B_FOUR);
		if (asList != null && asList.size() > 0 ) {
			print(response, Msg.EXISTS);
			return;
		}
		// 1.判断是否有审核权限 查询流程配置表
		List<AuditStatus> auList = asDAO.findByRcMcBusiness(cu_roleCode(request), Integer.parseInt(code), Sys.B_FOUR);
		if (auList == null || auList.size() == 0) {
			print(response, Msg.ERROR);
			return;
		}
		Reimburse re = reDAO.get(Integer.parseInt(code));
		//判断角色是否为彭总  是则走彭总审核 不是则走普通审核
		Integer rrc = roleDAO.findName("总经理", organDAO.getRoot(cu_organCode(request)).getCode());
		Integer rc2 = roleDAO.findName("出纳", organDAO.getRoot(cu_organCode(request)).getCode());
		if(cu_roleCode(request) == rrc){
			//根据编号的到上级审核数据
			AuditStatus aus = asDAO.findMcRc(Integer.parseInt(code), rc2, Sys.B_FOUR);
			aus.setStatus(Sys.B_ONE);
			asDAO.upd(aus);
			AuditStatus aus1 = asDAO.findMcRc(Integer.parseInt(code), rrc, Sys.B_FOUR);
			aus1.setAt(new Date());
			aus1.setAu(cu_code(request));
			aus1.setStatus(Sys.B_ONE);
			asDAO.upd(aus1);
			
			
			re.setPass(Sys.B_THREE);
			re.setPt(new Date());
			reDAO.upd(re);
			List<ReimburseItem> item = reDAO.findApplyItem(Integer.parseInt(code));
			re.setItemList(item);
			String content = mtDAO.throughToCu(re.getCt(), new Date());
			msgDAO.sendToUsers("【" + cu_realName(request) + "】审核通知", content, cu_code(request), cu_organCode(request), re.getCu());
			print(response,Msg.SUCCESS);
		}else{
			// 判断是否有上一级审核
			//Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
			Integer ishave = asDAO.ishave(cu_roleCode(request), Integer.parseInt(code), Sys.B_FOUR, organDAO.getSonCodeList(cu_organCode(request)));
			if (ishave !=null && ishave > 1) {
				// 2.判断上一级审核节点是否已经审核通过，查询流程配置表和审核状态表
				Byte beforeStatus = asDAO.checkBeforeByBusinessRc(Sys.B_FOUR, cu_roleCode(request), organDAO.getSonCodeList(cu_organCode(request)), Integer.parseInt(code));
				// 3.有审核权限，且上一级审核节点已经审核通过，进行保存本次审核状态
				if (beforeStatus == null || beforeStatus != Sys.B_ONE) {
					print(response, Msg.PARAMETER_ERROR);
					return;
				}
			}
			if (null != code) {
				List<AuditStatus> asList1 = reDAO.findAuditStatusBusiness(Integer.parseInt(code), cu_roleCode(request), Sys.B_FOUR);
				for (AuditStatus as : asList1) {
					as.setStatus(Sys.B_ONE);
					as.setAu(cu_code(request));
					as.setAt(new Date());
					result = asDAO.upd(as);
					// 查询是否有下一节点，有就修改下一节点审核状态为当前审核状态并发送消息通知下一审核人，没有就通知申请提交人
					List<AuditStatus> pcList = asDAO.findByOcPcMcBusiness(as.getPc() + 1, Integer.parseInt(code), Sys.B_FOUR);
					if (null != pcList && pcList.size() > 0) {
						for(AuditStatus aud : pcList){
							aud.setBeforeStatus(Sys.B_ONE);
							result = asDAO.upd(aud);
							Integer rc1 = userDAO.findByOc(aud.getCu(),aud.getOc());
							//下一节点审核人角色和申请人角色相同则直接通过，不相等则直接通知下一审核人
							if (null != rc1 && rc1 == aud.getRc()){
								aud.setStatus(Sys.B_ONE);
								aud.setAt(new Date());
								aud.setAu(aud.getCu());
								aud.setBeforeStatus(Sys.B_ONE);
								result = asDAO.upd(aud);
								// 查询是否有下一节点，有就修改下一节点审核状态为当前审核状态并发送消息通知下一审核人，没有就通知申请提交人
								List<AuditStatus> pc1List = asDAO.findByOcPcMcBusiness(aud.getPc() + 1, Integer.parseInt(code), Sys.B_FOUR);
								if (null != pcList && pcList.size() > 0) {
									for(AuditStatus ad : pc1List){
										ad.setBeforeStatus(Sys.B_ONE);
										result = asDAO.upd(ad);
									}
									//消息通知审核人
									String name =userDAO.findCode(aud.getAu());
									Integer rc = asDAO.findByMcOcPc(aud.getOc(), aud.getMc(), aud.getPc() + 1);	// 获取该机构具有审核申请信息的角色编号
									if(null == rc ){
										print(response, Msg.ERROR);
										return;
									}
									List<UserInfo> userList = userDAO.findByRoleRc(cu_organCode(request), rc);	// 获取有审核角色的所有用户
									List<Integer> rucs = new ArrayList<Integer>();
									for (UserInfo u : userList) {
										rucs.add(u.getCode());
									}
									List<ReimburseItem> item = reDAO.findApplyItem(Integer.parseInt(code));
									re.setItemList(item);
									String content = mtDAO.applyFirstToTwo(re, re.getCn(), cu_realName(request), aud.getCt());
									msgDAO.sendToUsers("【" + name + "】提交申请单待审核通知", content, as.getCu(), cu_organCode(request), rucs);
									print(response,Msg.SUCCESS);
								} else {
									re.setPass(Sys.B_THREE);
									re.setPt(new Date());
									reDAO.upd(re);
									List<ReimburseItem> item = reDAO.findApplyItem(Integer.parseInt(code));
									re.setItemList(item);
									String content = mtDAO.throughToCu(re.getCt(), as.getAt());
									msgDAO.sendToUsers("【" + cu_realName(request) + "】审核通知", content, cu_code(request), cu_organCode(request), re.getCu());
									print(response,Msg.SUCCESS);
								}
							} else {
								 //消息通知审核人
								Integer rc = asDAO.findByMcOcPc(as.getOc(), as.getMc(), as.getPc() + 1);	// 获取该机构具有审核申请信息的角色编号
								if(null == rc ){
									print(response, Msg.ERROR);
									return;
								}
								List<UserInfo> userList = userDAO.findByRoleRc(cu_organCode(request), rc);	// 获取有审核角色的所有用户
								List<Integer> rucs = new ArrayList<Integer>();
								for (UserInfo u : userList) {
									rucs.add(u.getCode());
								}
								List<ReimburseItem> item = reDAO.findApplyItem(Integer.parseInt(code));
								re.setItemList(item);
								String content = mtDAO.applyFirstToTwo(re, re.getCn(), cu_realName(request), as.getAt());
								msgDAO.sendToUsers("【" + cu_realName(request) + "】提交申请单待审核通知", content, cu_code(request), cu_organCode(request), rucs);
								print(response,Msg.SUCCESS);
							}
						}
					} else if (RESULT.SUCCESS == result) {
						re.setPass(Sys.B_THREE);
						re.setPt(new Date());
						reDAO.upd(re);
						List<ReimburseItem> item = reDAO.findApplyItem(Integer.parseInt(code));
						re.setItemList(item);
						String content = mtDAO.throughToCu(re.getCt(), as.getAt());
						msgDAO.sendToUsers("【" + cu_realName(request) + "】审核通知", content, cu_code(request), cu_organCode(request), re.getCu());
						print(response,Msg.SUCCESS);
					}
				}
			}
		}
	}
	
	@RequestMapping(Url.UPDATEDESIGNATE_2)
	public void updateDesignate2(String code, String remark,HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 查询当前申请信息是否已被当前用户审核
		List<AuditStatus> asList =  asDAO.findByRcMcAuBusiness(cu_roleCode(request), Integer.parseInt(code), cu_code(request),Sys.B_FOUR);
		if (asList == null || asList.size() > 0) {
			print(response, Msg.EXISTS);
			return;
		}
		// 1.判断是否有审核权限 查询流程配置表
		List<AuditStatus> auList = asDAO.findByRcMcBusiness(cu_roleCode(request), Integer.parseInt(code), Sys.B_FOUR);
		if (auList == null || auList.size() < 0) {
			print(response, Msg.ERROR);
			return;
		}
		Reimburse re = reDAO.get(Integer.parseInt(code));
		//判断角色是否为彭总  是则走彭总审核 不是则走普通审核
		Integer rrc = roleDAO.findName("总经理", organDAO.getRoot(cu_organCode(request)).getCode());
		Integer rc2 = roleDAO.findName("出纳", organDAO.getRoot(cu_organCode(request)).getCode());
		Integer rrc1 =cu_roleCode(request);
		if(rrc1 == rrc){
			//根据编号的到上级审核数据
			AuditStatus aus = asDAO.findMcRc(Integer.parseInt(code), rc2, Sys.B_FOUR);
			aus.setStatus(Sys.B_TWO);
			asDAO.upd(aus);
			AuditStatus aus1 = asDAO.findMcRc(Integer.parseInt(code), rrc, Sys.B_FOUR);
			aus1.setAt(new Date());
			aus1.setAu(cu_code(request));
			aus1.setStatus(Sys.B_TWO);
			aus1.setRemark(remark);
			asDAO.upd(aus1);
			
			re.setPass(Sys.B_TWO);
			re.setPt(new Date());
			reDAO.upd(re);
			
			List<ReimburseItem> item = reDAO.findApplyItem(Integer.parseInt(code));
			re.setItemList(item);
			String content = mtDAO.rejectTofirst(re, cu_realName(request),aus1.getCt(), aus1.getRemark());
			msgDAO.sendToUsers("【" + cu_realName(request) + "】驳回了申请单", content, cu_code(request), cu_organCode(request), re.getCu());
			print(response,Msg.SUCCESS);
		}else{
			// 判断是否有上一级审核
			//Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
			Integer ishave = asDAO.ishave(cu_roleCode(request), Integer.parseInt(code), Sys.B_FOUR, organDAO.getSonCodeList(cu_organCode(request)));
			if (ishave !=null && ishave > 1) {
				// 2.判断上一级审核节点是否已经审核通过，查询流程配置表和审核状态表
				Byte status = asDAO.checkBeforeByBusinessRc(Sys.B_FOUR, cu_roleCode(request), organDAO.getSonCodeList(cu_organCode(request)), Integer.parseInt(code));
				// 3.有审核权限，且上一级审核节点已经审核通过，进行保存本次审核状态
				if (status == null || status != Sys.B_ONE) {
					print(response, Msg.PARAMETER_ERROR);
					return;
				}
			}
			if (null != code) {
				List<AuditStatus> asList1 = reDAO.findAuditStatusBusiness(Integer.parseInt(code), cu_roleCode(request),Sys.B_FOUR);
				re.setPass(Sys.B_TWO);
				re.setPt(new Date());
				reDAO.upd(re);
				for (AuditStatus as : asList1) {
					as.setStatus(Sys.B_TWO);
					as.setAu(cu_code(request));
					as.setAt(new Date());
					as.setRemark(remark);
					if (RESULT.SUCCESS == asDAO.upd(as)) {
						List<ReimburseItem> item = reDAO.findApplyItem(Integer.parseInt(code));
						re.setItemList(item);
						String content = mtDAO.rejectTofirst(re, cu_realName(request),as.getCt(), as.getRemark());
						msgDAO.sendToUsers("【" + cu_realName(request) + "】驳回了申请单", content, cu_code(request), cu_organCode(request), re.getCu());
						print(response,Msg.SUCCESS);
					}
				}
			}
		}
	}
	
	
	// 移交彭总
	@RequestMapping(value = Url.TRANSFER)
	public void transfer(Integer code,Integer pc, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code && pc != null) {
			Reimburse a = reDAO.get(code);
			Integer rc = roleDAO.findName("总经理", organDAO.getRoot(cu_organCode(request)).getCode());
			if (null != a) {
				AuditStatus aus = asDAO.findMcRc(code, cu_roleCode(request), Sys.B_FOUR);
				aus.setAu(cu_code(request));
				aus.setAt(new Date());
				asDAO.upd(aus);
				AuditStatus as = new AuditStatus();
				as.setMc(code);
				as.setCu(a.getCu());
				as.setCt(a.getCt());
				as.setOc(a.getOc());
				as.setBusiness(Sys.B_FOUR);
				as.setRc(rc);
				as.setPc(pc + 1);
				as.setBeforeStatus(Sys.B_ONE);
				asDAO.add(as);
				print(response,Msg.SUCCESS);
			}
		}
	}
	
	
	@Autowired
	public void setReDAO(ReimburseDAO reDAO) {
		this.reDAO = reDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setAsDAO(AuditStatusDAO asDAO) {
		this.asDAO = asDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	@Autowired
	public void setMtDAO(MessageTemplateDAO mtDAO) {
		this.mtDAO = mtDAO;
	}
	@Autowired
	public void setMsgDAO(MessageDAO msgDAO) {
		this.msgDAO = msgDAO;
	}
	@Autowired
	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}
	
}
